package com.admin.system.modules.system.rest;

import com.admin.common.constant.ExceptionConstant;
import com.admin.common.entity.BaseEntity;
import com.admin.common.enums.DataScopeEnum;
import com.admin.common.exception.BadRequestException;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.core.dto.RoleQueryDTO;
import com.admin.core.entity.SysMenu;
import com.admin.core.entity.SysRole;
import com.admin.core.entity.SysUserRole;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.oauth.util.DataScopeUtil;
import com.admin.system.modules.system.service.RoleMenuService;
import com.admin.system.modules.system.service.RoleService;
import com.admin.system.modules.system.service.UserRoleService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：角色管理")
@RequestMapping("/api/roles")
public class RoleController {

    private final RoleService roleService;
    private final RoleMenuService roleMenuService;
    private final UserRoleService userRoleService;

    @ApiOperation("分页查询")
    @GetMapping
    @PreAuthorize("@ss.check('roles:list')")
    public ResponseEntity<PageResult<SysRole>> paging(RoleQueryDTO dto) {
        return new ResponseEntity<>(roleService.paging(dto), HttpStatus.OK);
    }

    @ApiOperation("根据ID获取")
    @GetMapping(value = "/{id}")
    @PreAuthorize("@ss.check('roles:list')")
    public ResponseEntity<SysRole> getById(@PathVariable Integer id) {
        return new ResponseEntity<>(roleService.getById(id), HttpStatus.OK);
    }

    @ApiOperation("提供给用户列表")
    @GetMapping(value = "/showUserList")
    public ResponseEntity<List<SysRole>> showUserList(Integer userId) {
        Set<SysRole> set = new TreeSet<>(Comparator.comparing(SysRole::getId));
        List<SysRole> roles = roleService.list(new RoleQueryDTO());
        set.addAll(roles);
        if (userId != null) {
            List<SysRole> temp = roleService.listByUsersId(userId);
            set.addAll(temp);
        }
        return new ResponseEntity<>(new ArrayList<>(set), HttpStatus.OK);
    }

    @Log(module = "角色管理", operateType = OperateTypeEnum.ADD)
    @ApiOperation("新增")
    @PostMapping
    @PreAuthorize("@ss.check('roles:add')")
    public ResponseEntity<Object> add(@Validated @RequestBody SysRole entity) {
        if (entity.getId() != null) {
            throw new BadRequestException(ExceptionConstant.ERROR_PARAM);
        }
        roleService.add(entity);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log(module = "角色管理", operateType = OperateTypeEnum.MODIFY)
    @ApiOperation("修改")
    @PutMapping
    @PreAuthorize("@ss.check('roles:edit')")
    public ResponseEntity<Object> modify(@Validated(BaseEntity.Update.class) @RequestBody SysRole entity) {
        roleService.modify(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "角色管理", operateType = OperateTypeEnum.MODIFY, description = "修改角色菜单")
    @ApiOperation("修改角色菜单")
    @PutMapping(value = "/menu")
    @PreAuthorize("@ss.check('roles:edit')")
    public ResponseEntity<Object> updateRoleMenu(@RequestBody SysRole entity) {
        roleService.updateMenu(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "角色管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation("删除")
    @DeleteMapping
    @PreAuthorize("@ss.check('roles:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<Integer> ids) {
        // 验证是否被用户关联
        if (userRoleService.count(Wrappers.<SysUserRole>lambdaQuery().in(SysUserRole::getRoleId, ids)) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请先解除");
        }
        roleService.remove(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('role:list')")
    public void export(HttpServletResponse response, RoleQueryDTO dto) throws IOException {
        List<SysRole> roles = roleService.list(dto);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysRole role : roles) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", role.getName());
            map.put("数据权限", DataScopeEnum.getLabelByValue(role.getDataScope()));
            map.put("描述", role.getDescription());
            map.put("创建日期", role.getCreateTime());
            list.add(map);
        }
        MultipartFileUtil.downloadExcel(list, response);
    }

    @ApiOperation("根据角色获取菜单")
    @GetMapping(value = "/menus/{id}")
    @PreAuthorize("@ss.check('roles:edit')")
    public ResponseEntity<List<SysMenu>> menus(@PathVariable int id) {
        return new ResponseEntity<>(roleMenuService.listMenuByRoleId(id), HttpStatus.OK);
    }

    @ApiOperation("数据范围")
    @GetMapping(value = "/dataScope")
    @PreAuthorize("@ss.check('roles:add', 'roles:edit')")
    public ResponseEntity<JSONArray> dataScope() {
        Map<Integer, String> map = DataScopeUtil.show();
        JSONArray array = new JSONArray();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value", entry.getKey());
            jsonObject.put("label", entry.getValue());
            array.add(jsonObject);
        }
        return new ResponseEntity<>(array, HttpStatus.OK);
    }

}
